import React, { Component } from 'react';
import sha1 from 'sha1';
import FilePanel from 'components/diffPanel';
import Conversation from 'pages/index/pages/project/pages/projectMergeRequestDetail/pages/changes/containers/components/diff/conversation';
import { navigate } from 'utils/router';
import RuleCard from 'components/ruleCard/rule';
import { Checkbox } from '@teamix/ui';

import './index.scss';
import intl from '../../../../../../../../../../locale';

export default class LogDiff extends Component {
  handleGoFile = (firstNote, issue, isIssueOutdated) => {
    // 云豆过期不跳转
    if (isIssueOutdated) {
      return;
    }
    const { pathResource, codeReviewDetail } = window.FORCE;
    const curPath = `/${pathResource.fullPath}/merge_request/${codeReviewDetail.id}`;
    const { line, side } = issue
      ? { line: issue.begin_line, side: 'right' }
      : this.props.getLineInfo(firstNote);
    navigate(`${curPath}/changes`);

    this.props.changeMrTabKey('changes');
    // 回复云豆时
    if (issue) {
      window.location.hash = `#file=${sha1(issue.file_name)}&line=${line}&side=${side}`;
      return;
    }

    let range_context = '';
    try {
      const { inline_comments } = this.props.changesReducer;
      const curComment = inline_comments.find((item) => {
        return item.id === firstNote.id;
      });
      if (curComment.outdated) {
        let [from_commit, to_commit] = curComment.range_context.split(' ');
        if (from_commit && !to_commit) {
          to_commit = from_commit;
        }
        if (to_commit && !from_commit) {
          from_commit = to_commit;
        }
        range_context = `&from_commit=${from_commit}&to_commit=${to_commit}`;
      }
    } catch (err) {
      console.error(err);
    }

    window.location.hash = `#file=${sha1(
      firstNote.new_path,
    )}&line=${line}&side=${side}${range_context}`;
  };

  renderNote(curNoteData, index) {
    const firstData = curNoteData;
    const firstNote = firstData.noteList[0];
    // 回复云豆从issue获取信息，普通评论则从评论中获取
    const { issue } = curNoteData;
    const { line, side, to_commit, from_commit, closed, id } = issue
      ? { line: issue.begin_line, side: 'right', from_commit: '', to_commit: '' }
      : this.props.getLineInfo(firstNote);
    const conversation = firstData.noteList.map((item) => {
      if (!item.author) {
        item.author = {
          avatar_url: item.author_avatar_url,
          extern_uid: item.author_extern_uid,
          id: item.author_id,
          name: item.author_name,
          state: item.author_state,
          username: item.author_username,
        };
      }
      return item;
    });

    let extraInfo = '';
    const isIssueOutdated = issue && issue.status && issue.status.toLowerCase() === 'resolved';
    if (isIssueOutdated) {
      extraInfo = intl.get({
        id: 'code-assets.logs.comment.inlineComment.Expired',
        defaultMessage: '已过期',
      });
    } else if (line) {
      extraInfo = intl.get(
        {
          id: 'code-assets.logs.comment.inlineComment.LineLine',
          defaultMessage: '第{line}行',
        },
        { line },
      );
    }
    const curPath = issue ? issue.file_name : firstNote.new_path;

    return (
      <div style={{ marginTop: index === 0 ? 0 : 16 }}>
        <FilePanel noBorderRadius id={`log_file_${curPath ? sha1(curPath) : ''}`}>
          <FilePanel.Header>
            <div className="log-detail-file-header">
              <div className="title">
                <a
                  className={`log-file-name ${isIssueOutdated ? 'outdated' : ''}`}
                  onClick={() => {
                    this.handleGoFile(firstNote, issue, isIssueOutdated);
                  }}
                >
                  {issue ? issue.file_name : firstNote.new_path}
                  <span>&nbsp;{extraInfo}</span>
                </a>
              </div>
              {/* 云豆无需解决 */}
              {!issue && (
                <Checkbox
                  checked={!!closed}
                  onChange={() => {
                    this.props.toggleComment({ noteId: id, closed: !closed });
                  }}
                  className="discuss-checkbox"
                  style={{ marginRight: '5px' }}
                >
                  {closed
                    ? intl.get({
                        id: 'code-assets.logs.comment.inlineComment.Resolved',
                        defaultMessage: '已解决',
                      })
                    : intl.get({
                        id: 'code-assets.logs.comment.inlineComment.ToBeResolved',
                        defaultMessage: '待解决',
                      })}
                </Checkbox>
              )}
            </div>
          </FilePanel.Header>
          <FilePanel.Body noPadding>
            <div className="log-detail-file-body">
              {issue ? (
                <div>
                  <RuleCard
                    rule={issue}
                    author={{
                      name: intl.get({
                        id: 'code-assets.logs.comment.inlineComment.KidneyBeans',
                        defaultMessage: '云豆',
                      }),
                      avatar_url:
                        'https://img.alicdn.com/tfs/TB1WYSpIQL0gK0jSZFtXXXQCXXa-400-401.png',
                    }}
                    commentEle={
                      <Conversation
                        {...{
                          conversation,
                          line,
                          side: 'right',
                          newpath: issue.file_name,
                          readOnly: conversation[0] && conversation[0].is_draft,
                          issueId: issue.id,
                          isYundouComment: true,
                          ...this.props,
                          noDraft: true,
                        }}
                      />
                    }
                  />
                </div>
              ) : (
                <Conversation
                  issueId={issue ? issue.id : ''}
                  conversation={conversation}
                  to_commit={to_commit}
                  from_commit={from_commit}
                  line={line}
                  noDraft
                  side={side}
                  {...this.props}
                />
              )}
            </div>
          </FilePanel.Body>
        </FilePanel>
      </div>
    );
  }

  render() {
    const { log } = this.props;
    const { noteData } = log;
    return (
      <div className="">
        {noteData.map((item, index) => {
          return this.renderNote(item, index);
        })}
      </div>
    );
  }
}
